#include <vector>
#include <functional>
#include <pthread.h>

#include "Sock.hpp"




typedef std::function<void(int)> func_t ;

class TcpServer ; 

class ThreadData
{
public:

    int _sock ;
    TcpServer* _server ;  // 为了访问服务端信息 

public:

    ThreadData(int sock, TcpServer* server)
    :_sock(sock)
    ,_server(server)
    {

    }

    ~ThreadData()
    {

    }
};


//初始化网络通信信息 ， 调用线程执行方法
class TcpServer
{
private:

    int _listensock ;
    Sock _sock ; 
    std::vector<func_t> _funcs ;

private:

    static void* ThreadRoutine(void* args )
    {
        pthread_detach(pthread_self());
        ThreadData* td = static_cast<ThreadData*> (args); //类型转换
        td->_server->Excute(td->_sock);
        close(td->_sock); // ? ? ? ? ? 
        return nullptr ;
    }

public:

    TcpServer(const uint16_t& port, const std::string& ip = "0.0.0.0")
    {
        _listensock = _sock.Socket();
        _sock.Bind(_listensock, port, ip);
        _sock.Listen(_listensock);
    }

    void BindService(func_t func)
    {
        _funcs.push_back(func);
    }

    //? ? ? ? 
    void Excute(int sock)
    {
        for(auto& f : _funcs)
        {
            f(sock);// ? ? ? ? ?
        }
    }

    void Start()
    {
        for(;;)
        {
            std::string clientip ;
            uint16_t clientport ;
            int sock = _sock.Accept(_listensock, &clientip, &clientport);
            if(sock == -1)
            {
                continue;
            }
            logMessage(NORMAL, "create new link success, sock: %d", sock);
            pthread_t tid ;
            ThreadData* td = new ThreadData(sock, this); //? ? ? ? ? ?
            pthread_create(&tid, nullptr, ThreadRoutine , (void*)td); //? ? ? ? ? ? ? // td
        }
    }

    ~TcpServer()
    {
        // 。。。。。。。。
        if (_listensock > 0)
            close(_listensock);
    }
};


